//
//  CAScrollerLayerImageView.m
//  CoreAnimation
//
//  Created by 张国文 on 16/10/17.
//  Copyright © 2016年 hangzhouyijiyin. All rights reserved.
//

#import "CAScrollerLayerImageView.h"

@interface CAScrollerLayerImageView ()

@property (nonatomic, assign) CGFloat recordWidthOffset;
@property (nonatomic, assign) CGFloat recordHeightOffset;

@end

@implementation CAScrollerLayerImageView

+ (Class)layerClass
{
    return [CAScrollLayer class];
}

- (instancetype)initWithFrame:(CGRect)frame
{
    if (self = [super initWithFrame:frame]) {
        self.userInteractionEnabled = YES;
        self.recordWidthOffset = 0.0;
        self.recordHeightOffset = 0.0;
        [self setUp];
    }
    return self;
}

- (void)setUp
{
    self.layer.masksToBounds = YES;
    UIPanGestureRecognizer *panRecogizer = [[UIPanGestureRecognizer alloc] initWithTarget:self action:@selector(pan:)];
    [self addGestureRecognizer:panRecogizer];
  //  [(CAScrollLayer *)self.layer scrollToPoint:CGPointMake(50, 50)];
}

- (void)pan:(UIPanGestureRecognizer *)recognier
{
    CGPoint offset = self.bounds.origin;
    CGPoint translate = [recognier translationInView:self];
    offset.x -= translate.x;
    offset.y -= translate.y;
    self.recordWidthOffset += translate.x;
    self.recordHeightOffset += translate.y;
    // 不会
    if (self.recordWidthOffset >= 0 && self.recordWidthOffset <= self.layer.sublayers.firstObject.frame.size.width && self.recordHeightOffset >= 0 && self.recordHeightOffset <= self.layer.sublayers.firstObject.frame.size.height) {
          [(CAScrollLayer *)self.layer scrollToPoint:offset];
    }
//    NSLog(@"x:%f,y:%f", [recognier translationInView:self].x, [recognier translationInView:self].y);
//    CGPoint subLayerPoint = [self.layer convertPoint:offset toLayer:self.layer.sublayers.firstObject];
//    NSLog(@"subLayerPoint = %@", [NSValue valueWithCGPoint:subLayerPoint]);
    
//    if (subLayerPoint.x < 0 || subLayerPoint.y < 0 || subLayerPoint.x > self.layer.sublayers.firstObject.frame.size.width || subLayerPoint.y > self.layer.sublayers.firstObject.frame.size.height) {
//        
//    } else {
//          [(CAScrollLayer *)self.layer scrollToPoint:offset];
//    }
  
   // self.transform = CGAffineTransformMakeTranslation([recognier translationInView:self].x, [recognier translationInView:self].y);
    [recognier setTranslation:CGPointZero inView:self];
}

@end
